package com.hwl.lab.controller;

import com.hwl.lab.entity.User;
import com.hwl.lab.entity.UserAndRole;
import com.hwl.lab.repository.UserAndRoleRepository;
import com.hwl.lab.service.UserService;
import com.hwl.lab.unit.Usercache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin //允许跨域请求
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserAndRoleRepository userAndRoleService;
    @Autowired
    private Usercache usercache;
    //查询所有
    @GetMapping("/findUserAll/{page}/{size}")
    public Page<User> findUserAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        return userService.findAll(page,size);
    }


    @GetMapping("/findByUserid/{userid}")
    public List<User> findByUserid(@PathVariable("userid") String userid){

        if (userService.findByUseridA(userid) == null) {
            return null;
        } else {
            List<User> users = new ArrayList<>();
            users.add(userService.findByUseridA(userid));
            return users;
        }
    }
    @GetMapping("findByUseridOne/{userid}")
    public User findByUseridOne(@PathVariable("userid") String userid) {
        return userService.findByUseridA(userid);
    }

    //添加，修改
    @PostMapping("/saveUser")
    public void saveUser(@RequestBody(required=false) User user){
        userService.saveUser(user);
    }

    //添加对应权限
    @PostMapping("/saveUserAndRole/{userid}/{rolename}")
    public void saveUserAndRole(@PathVariable("userid") String userid, @PathVariable("rolename") String rolename) {
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setUserid(userid);
        userAndRole.setRolename(rolename);
        userAndRoleService.save(userAndRole);
    }

    //通过账号删除
    @PostMapping("/deleteUser/{userid}")
    public void deleteById(@PathVariable("userid") String userid){
        userService.deleteByUserid(userid);
    }

    // 获取对应权限
    @PostMapping("/findByUseridU/{userid}")
    public String[] findByUseridU(@PathVariable("userid") String userid) {
        List<UserAndRole> userAndRoleslist = new ArrayList<>();
        userAndRoleslist = userAndRoleService.findRolenameByUserid(userid);
        String[] num = new String[20];
        for (int n = 0;n<userAndRoleslist.size();n++) {
            num[n] = userAndRoleslist.get(n).getRolename();
        }
      return   num;
    }

    // 级联删除对应权限
    @PostMapping("/deleteUserU/{userid}")
    public void deleteByIdU(@PathVariable("userid") String userid){
        userAndRoleService.deleteByUserid(userid);
    }

}
